/* eslint-disable n/no-process-exit */
// reload principle
// 当被watch的文件发生变化时，重新运行某个文件进程
// watcher.js
const { spawn } = require("node:child_process");
const fs = require("node:fs");
const chokidar = require("chokidar");
const fg = require("fast-glob");

const configs = [
  {
    name: "server",
    files: ["src/server/**/*.js", "config/server.json"],
    command: "node",
    args: ["server.js"],
  },
  {
    name: "client",
    files: ["src/client/**/*.js", "config/client.json"],
    command: "node",
    args: ["client.js"],
  },
];

for (const config of configs) {
  /**
   * @type {import("child_process").ChildProcess | null}
   */
  let cProcess = null;

  const startProcess = () => {
    if (cProcess) {
      cProcess.kill();
    }
    cProcess = spawn(config.command, config.args, { stdio: "inherit" });
    console.log(`[${config.name}] 进程已启动`);
  };

  // 初始启动
  startProcess();

  // 监听文件变化
  chokidar
    .watch(config.files)
    .on("change", (path) => {
      console.log(`[${config.name}] 文件变化: ${path}`);
      startProcess();
    })
    .on("error", (error) => {
      console.error(`[${config.name}] 监听错误:`, error);
    });
}

// 优雅退出
process.on("SIGINT", () => {
  console.log("正在关闭所有进程...");
  process.exit();
});
